package com.test.util;

import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class IPUtil {

    public static String search(String ip) throws IOException {
        // 1、创建 searcher 对象 (修改为离线库路径)
        String dbPath = "d:\\test\\ip2region.xdb";
        Searcher searcher = null;
        String region = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
            long sTime = System.nanoTime(); // Happyjava
            region = searcher.search(ip);
            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
        }finally {
            // 3、关闭资源
            if(searcher!=null){
                searcher.close();
            }
        }

        // 备注：并发使用，每个线程需要创建一个独立的 searcher 对象单独使用。

        return region;

    }

    public static void main(String[] args) throws Exception {
        String ip = "180.76.198.77";
        System.out.println(search(ip));
    }
}
